package com.hu.hrm.handler;

import com.alibaba.fastjson.JSON;
import com.hu.hrm.constants.MQConstants;
import com.hu.hrm.feignclients.FastdfsFeignClient;
import com.hu.hrm.util.MyFileUtils;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.util.Map;

//接收消息
@Component
public class PageStaticHandler {

    @Autowired
    private FastdfsFeignClient fastdfsFeignClient ;

    //监听页面静态化的队列
    @RabbitListener(queues = {MQConstants.NAME_QUEUE_PAGE_DIRECT})
    public void receiveEmail(String msg, Message message, Channel channel) throws IOException {
        //解析消息获取内容：1  2
        Map<String,String> map = JSON.parseObject(msg ,Map.class );
        //1.html在fastdfs下载路径
        String htmlPathInFastdfs = map.get("htmlPathInFastdfs");
        //2.nginx物理路径
        String physicalPath = map.get("physicalPath");

        //然后
        //从fastdfs下载html
        byte[] htmlBytes = fastdfsFeignClient.download(htmlPathInFastdfs);
        if(htmlBytes != null && htmlBytes.length > 0){
            //再  把html拷贝到nginx物理路径
            File file = MyFileUtils.createFile(physicalPath);
            FileCopyUtils.copy(htmlBytes ,file );

            //触发手动签收   修改为ture  避免可能有多个消费者的情况
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
